// @Desc:
// @CreateTime: 2020/11/16
package user

import (
	"net/http"

	"gitee.com/xuesongtao/gotool/xlog"
	"github.com/gin-gonic/gin"
	. "mycrm.com/controller"
	. "mycrm.com/module"
	"mycrm.com/module/user"
)

// usergrouplist
func GroupList(c *gin.Context) {
	var (
		resp         []map[string]interface{}
		groupId2Name []user.CrmUserGroup
	)
	Db.Table("crm_usergroup").Scan(&groupId2Name)
	for _, group := range groupId2Name {
		var (
			groupLeader string // 组长
			groupInfo   = make(map[string]interface{})
			groupNum    int64 // 组员个数
		)
		Db.Table("crm_user AS u").Joins("JOIN crm_user2role AS u2r ON u.id = u2r.user_id").Where("u.group_id = ? AND u2r.role_id=4", group.ID).Select("u.name").Scan(&groupLeader)
		Db.Table("crm_user").Where("group_id = ?", group.ID).Count(&groupNum)
		groupInfo["id"] = group.ID
		groupInfo["group_name"] = group.GroupName
		groupInfo["group_leader"] = groupLeader
		groupInfo["group_num"] = groupNum
		resp = append(resp, groupInfo)
	}
	xlog.Info("resp: ", resp)
	c.JSON(http.StatusOK, &Response{
		Status: 1,
		Data:   resp,
	})
}

func AddOrEditGroup(c *gin.Context) {
	var groupName user.CrmUserGroup
	if err := c.BindJSON(&groupName); err != nil {
		xlog.Error("c.BindJSON(&groupName) is failed, err: ", err)
	}
	action := c.Param("action")
	groupId := c.Query("group_id")
	xlog.Info("id: ", groupId)
	if action == "add" {
		Db.Model(&user.CrmUserGroup{}).Create(&groupName)
	} else {
		Db.Model(&user.CrmUserGroup{}).Where("id = ?", groupId).Update("group_name", groupName.GroupName)
	}
	c.JSON(http.StatusOK, &Response{
		Status: 1,
	})
}

func DelGroup(c *gin.Context) {
	groupId := c.Param("groupId")
	var (
		hasNum int64
		resp   = Response{
			Status: 1,
			Msg:    "",
		}
	)
	Db.Model(&user.CrmUser{}).Where("group_id = ?", groupId).Count(&hasNum)
	if hasNum > 0 {
		resp.Status = 0
		resp.Msg = "该分组有组员不能删除"
	} else {
		Db.Delete(&user.CrmUserGroup{}, groupId)
	}
	c.JSON(http.StatusOK, &resp)
}

func GetGroupInfo(c *gin.Context) {
	var groupInfo []user.CrmUserGroup
	Db.Model(&user.CrmUserGroup{}).Find(&groupInfo)
	c.JSON(http.StatusOK, &Response{
		Status: 1,
		Data:   groupInfo,
	})
}
